package com.ytd.smartcanteen.weighting.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.SwitchCompat;

import com.ytd.common.dialog.NormalDialog;
import com.ytd.common.util.AdbDebugUtil;
import com.ytd.common.util.DeviceUtil;
import com.ytd.common.util.FormatUtil;
import com.ytd.common.util.ToastUtil;
import com.ytd.smartcanteen.weighting.MainActivity;
import com.ytd.smartcanteen.weighting.adapter.ChooseListAdapter;
import com.ytd.smartcanteen.weighting.devices.LEDManager;
import com.ytd.smartcanteen.weighting.devices.ScaleManager;
import com.ytd.smartcanteen.weighting.devices.ScannerManager;
import com.ytd.smartcanteen.weighting.util.WeightConfig;

import java.util.ArrayList;
import java.util.Arrays;

import android_serialport_api.SerialPortFinder;
import cn.hutool.core.net.NetUtil;
import cn.ytd.smartcanteen.weighting.R;

public class PortDialog extends BaseDialog {
    MainActivity mActivity;
    EditText edit_led_bit, edit_scanner_bit, edit_scale_bit;
    Spinner sp_led_bit, sp_scanner_bit, sp_scale_bit;
    Button btnOK, btnBack;

    private final View mMenuView;

    private final SerialPortFinder mSerialPortFinder = new SerialPortFinder();
    private CheckBox mCheck_switch_price_sub;
    private View mPriceTimeHint;
    private EditText mEt_price_cal_time;
    private TextView mDebugStatus;


    @SuppressLint({"InflateParams", "UseCompatLoadingForDrawables"})
    public PortDialog(MainActivity context) {
        super(context);
        mActivity = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.dialog_port, null);
        mMenuView.findViewById(R.id.ll_show_device).setOnLongClickListener(v -> {
            Toast.makeText(mMenuView.getContext(), DeviceUtil.getDeviceSN(), Toast.LENGTH_LONG).show();
            return false;
        });
        SwitchCompat check_switch = mMenuView.findViewById(R.id.check_switch);
        check_switch.setChecked(WeightConfig.getAmountCheck());
        check_switch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            WeightConfig.setAmountCheck(isChecked);
            if (isChecked) {
                Toast.makeText(mActivity, "余额校验已开启", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mActivity, "余额校验已关闭", Toast.LENGTH_SHORT).show();
            }
        });
        initPrice();
        initEditText();
        initSpinner();
        initDebug();
        btnOK = mMenuView.findViewById(R.id.btn_login_ok);
        btnBack = mMenuView.findViewById(R.id.set_btn_back);
        int h = context.getWindowManager().getDefaultDisplay().getHeight();
        btnOK.setOnClickListener(v -> {
            setPort();
            setPriceTime();
            dismiss();
        });
        btnBack.setOnClickListener(v -> dismiss());

        mMenuView.findViewById(R.id.btn_scan_reset).setOnClickListener(v -> {
            NormalDialog dialog = new NormalDialog(mActivity, false);
            dialog.setText("请确认是否有扫码器维护手册？");
            dialog.setBtnText("确认", "取消");
            dialog.setCallBack(new NormalDialog.CallBack() {
                @Override
                public void dismiss() {

                }

                @Override
                public void onClickOk() {
                    ScannerManager.getInstance().sendReset();
                }
            });
            dialog.show();
        });

        mMenuView.findViewById(R.id.btn_scan_one).setOnClickListener(v -> ScannerManager.getInstance().sendSingle());
        mMenuView.findViewById(R.id.btn_scan_two)
            .setOnClickListener(v -> ScannerManager.getInstance().sendContinuous());
        this.setBackgroundDrawable(context.getResources().getDrawable(android.R.color.transparent));
        this.setContentView(mMenuView);
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        this.setHeight(h - 50);
        this.setFocusable(true);
        this.setOutsideTouchable(false);
        this.setAnimationStyle(R.style.DialogShow);
    }

    private void initDebug() {
        mDebugStatus = mMenuView.findViewById(R.id.tv_show_debug_status);
        updateDebugStatus();
        mMenuView.findViewById(R.id.btn_start_debug).setOnClickListener(v -> {
            AdbDebugUtil.start();
            updateDebugStatus();
        });
        mMenuView.findViewById(R.id.btn_end_debug).setOnClickListener(v -> {
            AdbDebugUtil.stop();
            updateDebugStatus();
        });
    }

    private void updateDebugStatus() {
        try {
            mDebugStatus.setText(AdbDebugUtil.check() ? "已开启\n" + NetUtil.getLocalhostStr() : "未开启");
        } catch (Throwable throwable) {
            mDebugStatus.setText("无网络");
        }
    }

    private void setPriceTime() {
        int time = getEditText(mEt_price_cal_time);
        if (time < 0) {
            time = 0;
            ToastUtil.showToast("最低0");
        }
        if (time > 500) {
            time = 500;
            ToastUtil.showToast("最大500");
        }
        WeightConfig.setPriceCalTime(time);
    }

    private void initPrice() {
        CheckBox mCheck_switch_price = mMenuView.findViewById(R.id.check_switch_price);
        mCheck_switch_price.setOnCheckedChangeListener((buttonView, isChecked) -> {
            WeightConfig.setCalPriceStable(isChecked);
            if (isChecked) {
                mCheck_switch_price_sub.setVisibility(View.GONE);
                mPriceTimeHint.setVisibility(View.GONE);
                mEt_price_cal_time.setVisibility(View.GONE);
            } else {
                mCheck_switch_price_sub.setVisibility(View.VISIBLE);
                mPriceTimeHint.setVisibility(View.VISIBLE);
                mEt_price_cal_time.setVisibility(View.VISIBLE);
            }
        });
        mCheck_switch_price_sub = mMenuView.findViewById(R.id.check_switch_price_sub);
        mCheck_switch_price_sub.setOnCheckedChangeListener((buttonView, isChecked) -> WeightConfig.setCalPriceSub(isChecked));
        mPriceTimeHint = mMenuView.findViewById(R.id.tv_price_time_hint);
        mEt_price_cal_time = mMenuView.findViewById(R.id.et_price_cal_time);
        mEt_price_cal_time.setText(String.valueOf(WeightConfig.getPriceCalTime()));
        mCheck_switch_price.setChecked(WeightConfig.getCalPriceStable());
        mCheck_switch_price_sub.setChecked(WeightConfig.getCalPriceSub());
    }


    @SuppressLint("SetTextI18n")
    private void initEditText() {
        edit_led_bit = mMenuView.findViewById(R.id.et_led_bit);
        edit_scale_bit = mMenuView.findViewById(R.id.et_scale_bit);
        edit_scanner_bit = mMenuView.findViewById(R.id.et_scanner_bit);
        int ledBit = WeightConfig.getLedBit();
        int scaleBit = WeightConfig.getScaleBit();
        int scannerBit = WeightConfig.getScannerBit();
        edit_led_bit.setText(ledBit + "");
        edit_scale_bit.setText(scaleBit + "");
        edit_scanner_bit.setText(scannerBit + "");
    }

    private void initSpinner() {
        sp_led_bit = mMenuView.findViewById(R.id.sp_led);
        sp_scale_bit = mMenuView.findViewById(R.id.sp_scale_card);
        sp_scanner_bit = mMenuView.findViewById(R.id.sp_scanner);
        String[] allDevicesPath = mSerialPortFinder.getAllDevicesPath();
        ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(allDevicesPath));
        sp_led_bit.setAdapter(new ChooseListAdapter(mActivity, arrayList));
        sp_scale_bit.setAdapter(new ChooseListAdapter(mActivity, arrayList));
        sp_scanner_bit.setAdapter(new ChooseListAdapter(mActivity, arrayList));
        String ledPath = WeightConfig.getLedPath();
        String scalePath = WeightConfig.getScalePath();
        String scannerPath = WeightConfig.getScannerPath();
        if (arrayList.contains(ledPath)) {
            sp_led_bit.setSelection(arrayList.indexOf(ledPath));
        }
        if (arrayList.contains(scalePath)) {
            sp_scale_bit.setSelection(arrayList.indexOf(scalePath));
        }
        if (arrayList.contains(scannerPath)) {
            sp_scanner_bit.setSelection(arrayList.indexOf(scannerPath));
        }
        AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Adapter adapter = parent.getAdapter();
                if (adapter instanceof ChooseListAdapter) {
                    ((ChooseListAdapter) adapter).setCurrentItem(position);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        };
        sp_led_bit.setOnItemSelectedListener(listener);
        sp_scale_bit.setOnItemSelectedListener(listener);
        sp_scanner_bit.setOnItemSelectedListener(listener);
    }

    private void setPort() {
        boolean isLedChange = false, isScaleChange = false, isScannerChange = false;
        int ledBit = WeightConfig.getLedBit();
        int scaleBit = WeightConfig.getScaleBit();
        int scannerBit = WeightConfig.getScannerBit();

        int ledBitText = getEditText(edit_led_bit);
        int scaleBitText = getEditText(edit_scale_bit);
        int scannerBitText = getEditText(edit_scanner_bit);
        if (ledBitText != ledBit) {
            WeightConfig.setLedBit(ledBitText);
            isLedChange = true;
        }
        if (scaleBitText != scaleBit) {
            WeightConfig.setScaleBit(scaleBitText);
            isScaleChange = true;
        }
        if (scannerBitText != scannerBit) {
            WeightConfig.setScannerBit(scannerBitText);
            isScannerChange = true;
        }
        String ledPath = WeightConfig.getLedPath();
        String scalePath = WeightConfig.getScalePath();
        String scannerPath = WeightConfig.getScannerPath();

        String ledItem = getAdapterItem(sp_led_bit.getAdapter());
        String scaleItem = getAdapterItem(sp_scale_bit.getAdapter());
        String scannerItem = getAdapterItem(sp_scanner_bit.getAdapter());
        if (!TextUtils.equals(ledPath, ledItem)) {
            WeightConfig.setLedPath(ledItem);
            isLedChange = true;
        }
        if (!TextUtils.equals(scalePath, scaleItem)) {
            WeightConfig.setScalePath(scaleItem);
            isScaleChange = true;
        }
        if (!TextUtils.equals(scannerPath, scannerItem)) {
            WeightConfig.setScannerPath(scannerItem);
            isScannerChange = true;
        }
        if (isLedChange) {
            LEDManager.getInstance().release();
            LEDManager.getInstance().init();
        }
        if (isScaleChange) {
            ScaleManager.getInstance().release();
            ScaleManager.getInstance().init();
        }
        if (isScannerChange) {
            ScannerManager.getInstance().release();
            ScannerManager.getInstance().init();
        }
    }

    private int getEditText(EditText editText) {
        Editable text = editText.getText();
        if (text != null && !TextUtils.isEmpty(text.toString()) && TextUtils.isDigitsOnly(text.toString())) {
            return FormatUtil.parseInt(text.toString());
        }
        return -1;
    }

    private String getAdapterItem(Adapter adapter) {
        if (adapter instanceof ChooseListAdapter) {
            return ((ChooseListAdapter) adapter).getCurrentItem();
        }
        return "";
    }

    public void show(int gravity, int x, int y) {
        showAtLocation(mMenuView, gravity, x, y);
    }
}
